<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/9/16
 */

namespace backend\models;

use yii\elasticsearch\ActiveRecord;

class ElasticSearch extends ActiveRecord
{
    public static function getDb()
    {
        return \Yii::$app->get('elasticsearch');
    }

    //索引
    public static function index()
    {
        return 'website';
    }

    //文档类型
    public static function type()
    {
        return '_doc';
    }

    public function attributes()
    {
        return ['title'];
    }

    public static function mapping()
    {
        return [
            static::type() => [
                'properties' => [
                    'title' => ['type' => 'string', "index" => "not_analyzed"],
                    'author' => ['type' => 'string', "index" => "not_analyzed"],
                    'comment' => ['type' => 'integer', "index" => "not_analyzed"],
                ]
            ],
        ];
    }

    /**
     * Set (update) mappings for this model
     */
    public static function updateMapping()
    {
        $db = self::getDb();
        $command = $db->createCommand();
        if (!$command->indexExists(self::index())) {
            $command->createIndex(self::index());
        }
        $command->setMapping(self::index(), self::type(), self::mapping());
    }

    public static function getMapping() {
        $db = static::getDb();
        $command = $db->createCommand();
        return $command->getMapping(static::index(), static::type(), static::mapping());
    }

    /**
     * Create this model's index
     */
    public static function createIndex() {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->createIndex(static::index(), [
            'settings' => ["number_of_shards" => 1, "number_of_replicas" => 1],//1个分片1个复制
            'mappings' => static::mapping(),
            //'warmers' => [ /* ... */ ],
            //'aliases' => [ /* ... */ ],
            //'creation_date' => '...'
        ]);
    }

    public function insertRecord()
    {
        $model = new self();
        $model->_id = '234';
        $model->title = 'dfsdfdsf';
        $model->save();
    }
}